package com.crealth.handler;

import java.io.File;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.db.CreditReportDb;
import com.crealth.memcached.UserCached;
import com.crealth.model.CompanyModel;
import com.crealth.model.CreditReportModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.StringUtil;
import com.crealth.utils.Utils;

public class CreditReportHandler {
	private static Logger errorLog = Logger.getLogger("error_log");

	public static NetMessageData saveCreditReport(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		//UserModel user = UserCached.selectUserByID(userID);
		CreditReportModel creditReport = new CreditReportModel();
		creditReport.parseFromJson(msgJson);
		String strSearchDay = Utils.getDbYearMonthDay(creditReport.getSearchDate());
		String sqlCondition = String.format("consumer_name='%s' AND `identity`='%s' AND dj_bank_time like '%s %%'", 
				creditReport.getConsumerName(), creditReport.getIdentity(), strSearchDay);
		List<CreditReportModel> creditRptls = CreditReportDb.selectCreditReportByCondition(sqlCondition);
		if (creditRptls != null && creditRptls.size() > 0) {
			creditReport.setId(creditRptls.get(0).getId());
		}
		if (creditReport.getId() > 0) {
			CreditReportDb.updateCreditReport(creditReport);
		} else {
			CreditReportDb.insertCreditReport(creditReport);
		}
		
		resJson.put("creditRpt", creditReport.toJSONObject());
		resJson.put("opUser", userID);
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		//int companyID = user.getCompanyID();
		//ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		//ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		
		return sendMsg;
	}
	
	public static NetMessageData searchCreditReport(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Branch_Mgr_Fu && 
				user.getPosition() != ConstantDefine.Customer_Service) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);		
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		CreditReportModel creditReport = new CreditReportModel();
		creditReport.parseFromJson(msgJson);		
		if (user.getPosition() == ConstantDefine.Branch_Mgr_Fu || 
			user.getPosition() == ConstantDefine.Branch_Mgr || 
			user.getPosition() == ConstantDefine.Customer_Service) {
			CompanyModel belognCompany = user.getBelongCompany();
			if (belognCompany != null) {
				creditReport.setSearchDepartment(belognCompany.getShortName());
			}
		}
		
		String strSql = "";
		String tempCmpStr = "";
		if (creditReport.getSearchDepartment().length() > 0) {
			tempCmpStr = "search_department = '" + creditReport.getSearchDepartment() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getKhjl().length() > 0) {
			tempCmpStr = "khjl = '" + creditReport.getKhjl() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getAjjl().length() > 0) {
			tempCmpStr = "ajjl = '" + creditReport.getAjjl() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getDjUser().length() > 0) {
			tempCmpStr = "dj_user = '" + creditReport.getDjUser() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getConsumerName().length() > 0) {
			tempCmpStr = "consumer_name LIKE '%" + creditReport.getConsumerName() + "%'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getSearchBank().length() > 0) {
			tempCmpStr = "search_bank = '" + creditReport.getSearchBank() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (creditReport.getConsumerPhone().length() > 0) {
			tempCmpStr = "consumer_phone = '" + creditReport.getConsumerPhone() + "'";
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (msgJson.containsKey("searchTimeBeg") && msgJson.containsKey("searchTimeEnd")) {
			long searchTimeBeg = msgJson.getLongValue("searchTimeBeg") * 1000;
			long searchTimeEnd = msgJson.getLongValue("searchTimeEnd") * 1000;
			tempCmpStr = String.format("search_date > FROM_UNIXTIME(%d) AND FROM_UNIXTIME(%d) > search_date", searchTimeBeg, searchTimeEnd);
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}
		if (msgJson.containsKey("djTimeBeg") && msgJson.containsKey("djTimeEnd")) {
			long djTimeBeg = msgJson.getLongValue("djTimeBeg") * 1000;
			long djTimeEnd = msgJson.getLongValue("djTimeEnd") * 1000;
			tempCmpStr = String.format("dj_bank_time > FROM_UNIXTIME(%d) AND FROM_UNIXTIME(%d) > dj_bank_time", djTimeBeg, djTimeEnd);
			strSql = StringUtil.combinationSql(strSql, tempCmpStr);
		}		
		if (strSql.length() == 0) {
			strSql = "TRUE";
		}
		
		JSONArray jsonArray = new JSONArray();
		List<CreditReportModel> creditReportls = CreditReportDb.selectCreditReportByCondition(strSql);
		for (CreditReportModel curRpt : creditReportls) {
			jsonArray.add(curRpt.toJSONObject());
		}
		resJson.put("creditReportls", jsonArray);
		resJson.put("opUser", userID);
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());		
		
		return sendMsg;
	}
	
	public static NetMessageData uploadCreditReport(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadCreditReport msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			errorLog.error("uploadCreditReport userID is 0");
			return null;
		}
		String dtype = msgJson.getString("dtype");
		int creditRptID = msgJson.getIntValue("creditRptID");
		String data = msgJson.getString("data");
		long curtm = System.currentTimeMillis();
		String rawFileName = msgJson.getString("fileName");
		String suffix = Utils.getFileSuffix(rawFileName);
		String fileName = "" + userID + "_" + curtm + "." + suffix;
		String fileDir = "";
		String osName = Utils.getOSName();		
		if (osName.startsWith("Window")) {
			fileDir = "./credit_report_file";
			Utils.checkAndCreateDir(fileDir);			
		} else {
			fileDir = "/datadisk/webhost/credit_report_file";
			Utils.checkAndCreateDir(fileDir);			
			File f = new File(fileDir);
	        f.setWritable(true, false);						
		}
		Utils.saveUploadFile(userID, dtype, data, 
				rawFileName, fileName, fileDir);
		
		CreditReportDb.updateCreditFile(creditRptID, fileName);
		
		int resCode = 0;		
		resJson.put("resCode", resCode);
		resJson.put("creditRptID", creditRptID);
		resJson.put("fileName", fileName);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData uploadCreditReportPicture(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadCreditReportPicture msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			errorLog.error("uploadCreditReportPicture userID is 0");
			return null;
		}
		String dtype = msgJson.getString("dtype");
		int creditRptID = msgJson.getIntValue("creditRptID");
		String data = msgJson.getString("data");
		long curtm = System.currentTimeMillis();
		String rawFileName = msgJson.getString("fileName");
		String suffix = Utils.getFileSuffix(rawFileName);
		String fileName = "" + userID + "_" + curtm + "." + suffix;
		String fileDir = "";
		String osName = Utils.getOSName();		
		if (osName.startsWith("Window")) {
			fileDir = "./credit_report_picture";
			Utils.checkAndCreateDir(fileDir);			
		} else {
			fileDir = "/datadisk/webhost/credit_report_picture";
			Utils.checkAndCreateDir(fileDir);			
			File f = new File(fileDir);
	        f.setWritable(true, false);					
		}
		Utils.saveUploadFile(userID, dtype, data, 
				rawFileName, fileName, fileDir);
		
		CreditReportDb.updatePictureFile(creditRptID, fileName);
		
		int resCode = 0;
		resJson.put("resCode", resCode);
		resJson.put("creditRptID", creditRptID);
		resJson.put("fileName", fileName);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	
	
}
